<template>
  <a-modal :width="modalWidth" :visible="visible" :title="title" @cancel="handleCancel" :confirm-loading="loading">
    <template slot="footer">
      <a-button key="back" @click="handleCancel">
        取消
      </a-button>
      <a-button v-if="action === 'edit'" key="submit" type="primary" :loading="loading" @click="handleOk">
        提交
      </a-button>
    </template>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          ref="myForm"
          :model="form"
          :rules="validatorRules"
          :label-col="{ style: { width: '150px' } }"
        >
          <a-row :gutter="24">
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="用户ID" prop="id">
                <a-input allowClear class="per100" disabled v-model="form.id" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="手机号码" prop="phone">
                <a-input
                  allowClear
                  class="per100"
                  :disabled="allDisabled"
                  :placeholder="getPlaceHolder"
                  v-model="form.phone"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="密码明文" prop="passwordPlaintext">
                <a-input
                  allowClear
                  class="per100"
                  :disabled="allDisabled"
                  :placeholder="getPlaceHolder"
                  v-model="form.passwordPlaintext"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="用户姓名" prop="realname">
                <a-input
                  allowClear
                  class="per100"
                  :disabled="allDisabled"
                  :placeholder="getPlaceHolder"
                  v-model="form.realname"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="用户昵称" prop="username">
                <a-input allowClear :placeholder="getPlaceHolder" :disabled="allDisabled" v-model="form.nickName" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="性別" prop="sex">
                <j-dict-select-tag
                  allowClear
                  :disabled="allDisabled"
                  v-model="form.sex"
                  :placeholder="getPlaceHolder"
                  dictCode="sex"
                  @input="
                    () => {
                      $refs.myForm.validateField('sex')
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="联系电话">
                <a-input
                  :disabled="allDisabled"
                  allowClear
                  class="per100"
                  :placeholder="getPlaceHolder"
                  v-model="form.telephone"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="QQ号码">
                <a-input :disabled="allDisabled" allowClear v-model="form.qqNum" :placeholder="getPlaceHolder" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="EMAIL">
                <a-input :disabled="allDisabled" allowClear v-model="form.email" :placeholder="getPlaceHolder" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="维护设备">
                <a-select
                  mode="multiple"
                  allowClear
                  :disabled="allDisabled"
                  placeholder="请选择"
                  v-model="form.deviceIds"
                >
                  <a-select-option v-for="item in machineOption" :key="item.deviceId">
                    {{ item.deviceName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import store from '@/store/'
import CommonApi from '@api/Common'
import { httpAction, getAction } from '@api/manage'
import { validateDuplicateValue } from '@/utils/util'
import AgentManage from '@api/AgentManage/AgentManage'

export default {
  name: 'DeviceAdd',
  inject: ['closeCurrent'],
  props: {
    model: {
      type: String,
      required: true,
      default: 'detail'
    },
    businessId: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    return {
      machineOption: [],
      form: {
        id: 0, // 商家id
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        phone: '', // 手机号
        realname: '', // 姓名
        withdrawalManualApproval: '0', //提现人工审批
        sex: 0, // 性别
        nickName: undefined, // 昵称
        agentModel: undefined,
        // 身份证
        wechatRealname: '', // 微信实名
        qqNum: '', // QQ号码
        email: '', // 电子邮件EMAIL
        createTime: '', // 创建日期
        lastLoginTime: undefined, // 最后登录时间
        address: undefined, // 地址
        detailAddress: undefined, // 详细地址
        postalCode: undefined, // 邮编
        status: 1, // 账户状态
        agentStatus: '0', // 代理商状态
        delFlag: 0,
        withdrawalMethod: '1', //提现方式
        deviceIds: [] // 维护设备id
      },
      loading: false,
      visible: false,
      title: '新增用户',
      action: '',
      url: {
        queryId: AgentManage.queryId,
        edit: AgentManage.edit,
        machineList: AgentManage.machineList
      },
      modalWidth: '80%',
      validatorRules: {
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'change' },
          {
            validator: this.validatePhone,
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('sys_user', 'phone', value, this.form.id, callback),
            trigger: 'blur'
          }
        ],
        realname: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        passwordPlaintext: [{ required: true, message: '密码明文不能为空', trigger: 'change' }],
        sex: [{ required: true, message: '性別不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    allDisabled() {
      return this.action === 'detail'
    },
    getPlaceHolder() {
      return this.allDisabled ? '' : '请输入'
    }
  },
  methods: {
    async showModal() {
      this.form.businessId = this.$props.businessId
      this.action = this.$props.model
      this.title = this.action === 'detail' ? '用户详情' : '编辑用户'
      this.getDetails()
      this.getMachineList()
      this.visible = true
    },

    handleCancel() {
      this.visible = false
    },

    getDetails() {
      if (!this.form.businessId) {
        return
      }
      getAction(this.url.queryId, { id: this.form.businessId })
        .then(res => {
          if (res.code === 0) {
            this.form = res.result
            if (this.form.deviceIds) {
              this.form.deviceIds = this.form.deviceIds.split(',')
            } else {
              this.form.deviceIds = []
            }

            console.log(this.form.deviceIds, 'this.form.deviceIds')
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    getMachineList() {
      getAction(this.url.machineList).then(res => {
        if (res.success) {
          this.machineOption = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },

    handleOk() {
      this.$refs.myForm.validate(valid => {
        if (valid) {
          this.loading = true
          const obj = JSON.parse(JSON.stringify(this.form))
          obj.deviceIds = obj.deviceIds.join()
          const data = Object.assign({}, obj)
          httpAction(this.url.edit, data, 'put')
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.handleCancel()
                this.$emit('ok')
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    validatePhone(rule, value, callback) {
      const reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/ // 电话号码
      const reg2 = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/ // 手机号
      if (reg1.test(value) || reg2.test(value)) {
        callback()
      } else {
        callback('请输入正确手机号码')
      }
    }
  }
}
</script>

<style scoped></style>

